/**
 * 仿真
 */
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { createGuid } from "@@/utils/tools";
import { customStomp } from "@@/utils/CustomStomp";
import { IStompFrame } from "@@/typings/stomp";
import { ISideStep, IBlueSideStep, IRedSideStep } from "@@/typings/observation";
import { IDeductControl, IFireAndInfo } from "@@/typings/deduct-control";
import { CustomViewer } from "@@/utils/CustomCesium/CustomCesium";
import ScenarioUtil from "@@/utils/Scenario";
import RoutesManager from "@@/utils/RoutesManager";
import moment from "moment";
import { Cartesian3, ConstantProperty } from "cesium";
import { IEntityInfoPanel, IEntityLogPanel } from "@@/typings/panel";
import PanelUtils from "@@/utils/PanelUtils";
import { EntityGroupId, FireGroupId, InfoGroupId } from "@@/enums/observation";
import DomainManager from "@@/utils/DomainManager";
// 直接导入各个 store，避免循环依赖
import { cesiumState } from "./cesium";

export interface SimulationState {
  // 一轮是否开始
  isStart: boolean;
  // 是否开始
  isPause: boolean;
  // 仿真时间
  simulTime: string;
  // 仿真速度
  simulSpeed: number;
  // 实时推演速度
  defSimulSpeed: number;
  //
  clientId: string;
  // 导演视角推演态势集合
  steps: ISideStep[];
  // 红方视角态势集合
  redSteps: ISideStep[];
  // 蓝方视角态势集合
  blueSteps: ISideStep[];
  // 当前视角
  currentPerspective: string;
  // 显示标签
  isShowLabel: boolean;
  // 是否显示路径
  isShowPath: boolean;
  // 是否显示状态栏
  isShowFooter: boolean;
  // 是否显示实体列表
  isShowEntityPanel: boolean;
  // 是否显示日志面板
  isShowLogPanel: boolean;
  isShowInfoDomain: boolean;
  isShowFireDomain: boolean;
  // 全视角是否首次加载
  allIsInit: boolean;
  // 红方是否首次加载
  redIsInit: boolean;
  // 蓝方是否首次加载
  blueIsInit: boolean;
  // 实时轨迹
  routesManager: null | RoutesManager;
  redDomainInit: boolean;
  blueDomainInit: boolean;
  // 信息域火力域
  domainManager: null | DomainManager;
  // 实体列表
  entityList: {
    red: IEntityInfoPanel[];
    blue: IEntityInfoPanel[];
  };
  // 日志
  entityLog: {
    red: IEntityLogPanel[];
    blue: IEntityLogPanel[];
  };
  entityIds: {
    red: string[];
    blue: string[];
  };
  // 存储火力信息域数据
  redFireSteps: IFireAndInfo[];
  blueFireSteps: IFireAndInfo[];
}

export const simulationState = defineStore("simulation-store", () => {
  const isStart = ref(false);
  const isPause = ref(true);
  const simulTime = ref("");
  const simulSpeed = ref(1.0);
  const defSimulSpeed = ref(1.0);
  const clientId = ref(createGuid());
  const currentPerspective = ref("all");
  const isShowLabel = ref(true);
  const isShowPath = ref(false);
  const isShowFooter = ref(true);
  const isShowEntityPanel = ref(false);
  const isShowLogPanel = ref(false);
  const isShowInfoDomain = ref(true);
  const isShowFireDomain = ref(true);
  const steps = ref<ISideStep[]>([]);
  const redSteps = ref<ISideStep[]>([]);
  const blueSteps = ref<ISideStep[]>([]);
  const redDomainInit = ref(true);
  const blueDomainInit = ref(true);
  const allIsInit = ref(true);
  const redIsInit = ref(true);
  const blueIsInit = ref(true);
  const routesManager = ref<null | RoutesManager>(null);
  const domainManager = ref<null | DomainManager>(null);
  const entityList = ref({
    red: [] as IEntityInfoPanel[],
    blue: [] as IEntityInfoPanel[]
  });
  const entityLog = ref({
    red: [] as IEntityLogPanel[],
    blue: [] as IEntityLogPanel[]
  });
  const entityIds = ref({
    red: [] as string[],
    blue: [] as string[]
  });
  // 存储火力信息域数据
  const redFireSteps = ref<IFireAndInfo[]>([]);
  const blueFireSteps = ref<IFireAndInfo[]>([]);

  const getIsPause = computed(() => isPause.value);
  const getSimulTime = computed(() => simulTime.value);
  const getSimulSpeed = computed(() => simulSpeed.value);

  // 修改为处理本地数据的方法
  function subscribeFireAndInformation(data: any) {
    const cesiumStore = cesiumState(),
      customViewer: CustomViewer | null = cesiumStore.getCustomViewer;

    if (customViewer === null) {
      return;
    }

    // 处理红方火力信息域数据
    if (data.redFireAndInfo) {
      // 保存红方火力信息域数据
      redFireSteps.value = Array.isArray(data.redFireAndInfo)
        ? data.redFireAndInfo
        : [data.redFireAndInfo];

      const redStep = redFireSteps.value[0];
      const visualAngle = "red";

      // 初始化红方域
      if (redDomainInit.value) {
        const { infoShow, fireShow } = getDomainShow("red");
        domainManager.value?.createInit(
          customViewer,
          redStep,
          visualAngle,
          fireShow,
          infoShow
        );
        redDomainInit.value = false;
      } else {
        updateDomainShow(customViewer);
        domainManager.value?.updatePath(customViewer, redStep, visualAngle);
      }
    }

    // 处理蓝方火力信息域数据
    if (data.blueFireAndInfo) {
      // 保存蓝方火力信息域数据
      blueFireSteps.value = Array.isArray(data.blueFireAndInfo)
        ? data.blueFireAndInfo
        : [data.blueFireAndInfo];

      const blueStep = blueFireSteps.value[0];
      const visualAngle = "blue";

      // 初始化蓝方域
      if (blueDomainInit.value) {
        const { infoShow, fireShow } = getDomainShow("blue");
        domainManager.value?.createInit(
          customViewer,
          blueStep,
          visualAngle,
          fireShow,
          infoShow
        );
        blueDomainInit.value = false;
      } else {
        updateDomainShow(customViewer);
        domainManager.value?.updatePath(customViewer, blueStep, visualAngle);
      }
    }
  }

  // 更新特定步骤的火力信息域
  function updateFireAndInfoAtStep(stepIndex: number) {
    const cesiumStore = cesiumState(),
      customViewer: CustomViewer | null = cesiumStore.getCustomViewer;

    if (!customViewer) return;

    // 更新红方火力信息域
    if (redFireSteps.value && redFireSteps.value.length > stepIndex) {
      const redData = redFireSteps.value[stepIndex];
      updateDomainShow(customViewer);
      domainManager.value?.updatePath(customViewer, redData, "red");
    }

    // 更新蓝方火力信息域
    if (blueFireSteps.value && blueFireSteps.value.length > stepIndex) {
      const blueData = blueFireSteps.value[stepIndex];
      updateDomainShow(customViewer);
      domainManager.value?.updatePath(customViewer, blueData, "blue");
    }
  }

  // 处理本地观察数据 - 替代原subscribeObservation方法
  async function processObservationData(stepIndex: number) {
    const cesiumStore = cesiumState(),
      customViewer: CustomViewer | null = cesiumStore.getCustomViewer;
    console.log(customViewer, 'customViewer')
    if (!customViewer) return null;

    try {
      // 使用类型断言避免类型错误
      const viewer = customViewer as any;

      // 获取当前步骤数据
      let currentStep = null;

      if (currentPerspective.value === 'all' && steps.value.length > stepIndex) {
        currentStep = steps.value[stepIndex];

        // 设置为非暂停状态
        isPause.value = false;

        // 处理全局视角数据
        if (allIsInit.value) {
          // 首次初始化
          const animations = ScenarioUtil.createInitAnimationsBySideStep(
            viewer,
            currentStep,
            "all"
          );

          if (animations) {
            const groupId = EntityGroupId.all;
            const group = viewer.animationManager?.createAnimationGroup(
              groupId,
              groupId,
              animations.period,
              animations.animations
            );
            if (group) {
              const result = await viewer.animationManager?.renderAnimationGroup(group);
              if (result && routesManager.value) {
                // 检查并使用正确的API创建初始路径
                if (typeof routesManager.value.createInitPath === 'function') {
                  await routesManager.value.createInitPath(currentStep, currentPerspective.value);
                } else if (typeof routesManager.value.initPath === 'function') {
                  await routesManager.value.initPath(currentStep, currentPerspective.value);
                } else {
                  console.warn('routesManager没有createInitPath或initPath方法');
                }

                setAllIsInit(false);
              }
            }
          }
        } else {
          // 更新已有数据
          const groupId = EntityGroupId.all;
          const group = viewer.animationManager?.getAnimationGroup(groupId);
          if (group) {
            ScenarioUtil.updateAnimationsBySideStep(
              viewer,
              group,
              currentStep,
              "all",
              false
            );

            if (routesManager.value) {
              // 检查并使用正确的API更新路径
              if (typeof routesManager.value.updatePath === 'function') {
                routesManager.value.updatePath(currentStep, currentPerspective.value);
              } else {
                // 尝试为每个实体添加路径点
                if (currentStep.obj_list && typeof routesManager.value.addPath === 'function') {
                  currentStep.obj_list.forEach(entity => {
                    const entityId = entity.m_id?.toString() || entity.entity_id;
                    let position;

                    // 检查位置数据的格式并处理
                    if (entity.m_Position) {
                      // 从1.json数据中提取位置
                      const longitude = entity.m_Position.longitude;
                      const latitude = entity.m_Position.latitude;
                      const height = entity.m_Position.height || 0;

                      // 创建Cartesian3坐标
                      const cartesian = Cartesian3.fromDegrees(
                        Number(longitude),
                        Number(latitude),
                        Number(height)
                      );

                      // 添加路径点
                      try {
                        routesManager.value.addPath(entityId, cartesian);
                      } catch (error) {
                        console.error(`添加路径点失败: ${entityId}`, error);
                      }
                    } else if (entity.position) {
                      const pos = entity.position.split(",");
                      if (pos && pos.length === 3) {
                        const cartesian = Cartesian3.fromDegrees(
                          Number(pos[0]),
                          Number(pos[1]),
                          Number(pos[2])
                        );

                        try {
                          routesManager.value.addPath(entityId, cartesian);
                        } catch (error) {
                          console.error(`添加路径点失败: ${entityId}`, error);
                        }
                      }
                    }
                  });
                }
              }
            }
          }
        }

        // 更新其他UI数据
        if (currentStep.simul_time) {
          simulTime.value = handleTimeDuration(currentStep.simul_time);
        }

        // 更新实体显示
        changeView(viewer, currentPerspective.value);
        if (routesManager.value) {
          routesManager.value.datasource.show = isShowPath.value;
        }
        return currentStep;
      }
      else if (currentPerspective.value === 'red' && redSteps.value.length > stepIndex) {
        currentStep = redSteps.value[stepIndex];

        // 处理红方视角数据
        if (redIsInit.value) {
          // 首次初始化红方视角
          const animations = ScenarioUtil.createInitAnimationsBySideStep(
            viewer,
            currentStep,
            "red"
          );

          if (animations) {
            const groupId = EntityGroupId.red;
            const group = viewer.animationManager?.createAnimationGroup(
              groupId,
              groupId,
              animations.period,
              animations.animations
            );

            if (group) {
              const result = await viewer.animationManager?.renderAnimationGroup(group);
              if (result) {
                setRedIsInit(false);
              }
            }
          }
        } else {
          // 更新已有红方数据
          const groupId = EntityGroupId.red;
          const group = viewer.animationManager?.getAnimationGroup(groupId);

          if (group) {
            ScenarioUtil.updateAnimationsBySideStep(
              viewer,
              group,
              currentStep,
              "red",
              false
            );
          }
        }

        // 更新视图
        changeView(viewer, currentPerspective.value);
        return currentStep;
      }
      else if (currentPerspective.value === 'blue' && blueSteps.value.length > stepIndex) {
        currentStep = blueSteps.value[stepIndex];

        // 处理蓝方视角数据
        if (blueIsInit.value) {
          // 首次初始化蓝方视角
          const animations = ScenarioUtil.createInitAnimationsBySideStep(
            viewer,
            currentStep,
            "blue"
          );

          if (animations) {
            const groupId = EntityGroupId.blue;
            const group = viewer.animationManager?.createAnimationGroup(
              groupId,
              groupId,
              animations.period,
              animations.animations
            );

            if (group) {
              const result = await viewer.animationManager?.renderAnimationGroup(group);
              if (result) {
                setBlueIsInit(false);
              }
            }
          }
        } else {
          // 更新已有蓝方数据
          const groupId = EntityGroupId.blue;
          const group = viewer.animationManager?.getAnimationGroup(groupId);

          if (group) {
            ScenarioUtil.updateAnimationsBySideStep(
              viewer,
              group,
              currentStep,
              "blue",
              false
            );
          }
        }

        // 更新视图
        changeView(viewer, currentPerspective.value);
        return currentStep;
      }

      return null;
    } catch (error) {
      console.error("处理观察数据时出错:", error);
      return null;
    }
  }

  // 加载本地数据
  function loadLocalData(data: any) {
    try {
      if (data.red && data.red.length > 0) {
        // 红方数据
        const redStepsData = data.red.map((item: any) => ({
          game_id: item.game_id || "default",
          simul_time: item.simul_time || 0,
          obj_list: item.obj_list || []
        }));
        const allStepsData = data.all.map((item: any) => ({
          game_id: item.game_id || "default",
          simul_time: item.simul_time || 0,
          obj_list: item.obj_list || []
        }));
        setRedSteps(redStepsData);

        // 全局视角
        setAllSteps(allStepsData);

        console.log(allStepsData, 'allStepsData')
        // 蓝方数据
        if (data.blue && data.blue.length > 0) {
          const blueStepsData = data.blue.map((item: any) => ({
            game_id: item.game_id || "default",
            simul_time: item.simul_time || 0,
            obj_list: item.obj_list || []
          }));
          setBlueSteps(blueStepsData);
        } else {
          setBlueSteps([]);
        }

        // 初始化实体列表
        initializeEntityList(redStepsData);

        // 处理火力信息域数据
        subscribeFireAndInformation(data);

        return true;
      }
      return false;
    } catch (error) {
      console.error("加载本地数据失败:", error);
      return false;
    }
  }

  // 应用指定步骤的数据
  function applyStepData(stepIndex: number) {
    // 根据当前视角获取对应的步骤数据
    let stepData;

    if (currentPerspective.value === 'red' && redSteps.value.length > stepIndex) {
      stepData = redSteps.value[stepIndex];
    } else if (currentPerspective.value === 'blue' && blueSteps.value.length > stepIndex) {
      stepData = blueSteps.value[stepIndex];
    } else if (steps.value.length > stepIndex) {
      stepData = steps.value[stepIndex];
    }

    if (!stepData) return null;

    // 更新仿真时间
    if (stepData.simul_time) {
      simulTime.value = moment
        .unix(Number(stepData.simul_time))
        .format("HH:mm:ss");
    }

    // 更新火力信息域
    updateFireAndInfoAtStep(stepIndex);

    return stepData;
  }

  // 初始化实体列表
  function initializeEntityList(allSteps: ISideStep[]) {
    // 收集所有实体信息
    const redEntitiesMap = new Map();
    const blueEntitiesMap = new Map();

    allSteps.forEach(step => {
      if (!step.obj_list) return;

      step.obj_list &&  step.obj_list.forEach((entity: any) => {
        const entityId = entity.m_id?.toString() || entity.entity_id;
        const alliance = entity.m_Side === 1 ? "Red" : (entity.alliance || "Blue");
        const entityName = entity.m_EntityName || entity.entity_name || "未命名实体";

        const entityInfo = {
          id: entityId,
          name: entityName,
          type: entity.entity_type || entity.m_EntityType || "未知类型",
          status: entity.action_status || "正常",
          // 其他需要的属性
        };

        if (alliance === "Red") {
          if (!redEntitiesMap.has(entityId)) {
            redEntitiesMap.set(entityId, entityInfo);
          }
        } else {
          if (!blueEntitiesMap.has(entityId)) {
            blueEntitiesMap.set(entityId, entityInfo);
          }
        }
      });
    });

    // 更新实体列表
    entityList.value = {
      red: Array.from(redEntitiesMap.values()),
      blue: Array.from(blueEntitiesMap.values())
    };

    // 更新实体ID列表
    entityIds.value = {
      red: Array.from(redEntitiesMap.keys()),
      blue: Array.from(blueEntitiesMap.keys())
    };
  }

  function updateDomainShow(customViewer: CustomViewer) {
    const fireGroupRed = customViewer.animationManager?.getAnimationGroup(
        FireGroupId.red
      ),
      fireGroupBlue = customViewer.animationManager?.getAnimationGroup(
        FireGroupId.blue
      ),
      infoGroupRed = customViewer.animationManager?.getAnimationGroup(
        InfoGroupId.red
      ),
      infoGroupBlue = customViewer.animationManager?.getAnimationGroup(
        InfoGroupId.blue
      );
    const redShow = getDomainShow("red");
    const blueShow = getDomainShow("blue");
    fireGroupRed && (fireGroupRed.datasource.show = redShow.fireShow);
    infoGroupRed && (infoGroupRed.datasource.show = redShow.infoShow);
    fireGroupBlue && (fireGroupBlue.datasource.show = blueShow.fireShow);
    infoGroupBlue && (infoGroupBlue.datasource.show = blueShow.infoShow);
  }

  function getDomainShow(visualAngle: string) {
    let infoShow = false;
    let fireShow = false;
    switch (currentPerspective.value) {
      case "red":
        if (visualAngle == "red") {
          if (isShowFireDomain.value) {
            fireShow = true;
          }
          if (isShowInfoDomain.value) {
            infoShow = true;
          }
        }
        break;
      case "blue":
        if (visualAngle == "blue") {
          if (isShowFireDomain.value) {
            fireShow = true;
          }
          if (isShowInfoDomain.value) {
            infoShow = true;
          }
        }
        break;
      case "all":
        if (isShowFireDomain.value) {
          fireShow = true;
        }
        if (isShowInfoDomain.value) {
          infoShow = true;
        }
        break;
    }
    return {
      infoShow,
      fireShow,
    };
  }

  function updateLabelShow(customViewer: CustomViewer) {
    const groupAll = customViewer.animationManager?.getAnimationGroup(
        EntityGroupId.all
      ),
      groupRed = customViewer.animationManager?.getAnimationGroup(
        EntityGroupId.red
      ),
      groupBlue = customViewer.animationManager?.getAnimationGroup(
        EntityGroupId.blue
      );
    if (groupAll) {
      groupAll.datasource.entities.values.forEach((entity) => {
        entity.label && (entity.label.show = new ConstantProperty(isShowLabel.value));
      });
    }
    if (groupRed) {
      groupRed.datasource.entities.values.forEach((entity) => {
        entity.label && (entity.label.show = new ConstantProperty(isShowLabel.value));
      });
    }
    if (groupBlue) {
      groupBlue.datasource.entities.values.forEach((entity) => {
        entity.label && (entity.label.show = new ConstantProperty(isShowLabel.value));
      });
    }
  }

  function addStep(step: ISideStep) {
    steps.value = [...steps.value, step];
  }

  function addRedStep(step: ISideStep) {
    redSteps.value = [...redSteps.value, step];
  }

  function addBlueStep(step: ISideStep) {
    blueSteps.value = [...blueSteps.value, step];
  }

  function setAllIsInit(flag: boolean) {
    allIsInit.value = flag;
  }
  function setRedIsInit(flag: boolean) {
    redIsInit.value = flag;
  }
  function setBlueIsInit(flag: boolean) {
    blueIsInit.value = flag;
  }

  function setIsPause(param: boolean) {
    isPause.value = param;
  }

  function setSimulTime(param: string) {
    simulTime.value = param;
  }

  function setSimulSpeed(param: number) {
    simulSpeed.value = param;
  }

  function restart(customViewer: CustomViewer) {
    setSimulSpeed(1);
    // 导演视角推演态势集合
    steps.value = [];
    // 红方视角态势集合
    redSteps.value = [];
    // 蓝方视角态势集合
    blueSteps.value = [];
    // 实体列表
    entityList.value = {
      red: [],
      blue: [],
    };
    // 日志
    entityLog.value = {
      red: [],
      blue: [],
    };
    // 实时轨迹
    routesManager.value && routesManager.value.removePath();

    const groupAll = customViewer.animationManager?.getAnimationGroup(
        EntityGroupId.all
      ),
      groupRed = customViewer.animationManager?.getAnimationGroup(
        EntityGroupId.red
      ),
      groupBlue = customViewer.animationManager?.getAnimationGroup(
        EntityGroupId.blue
      );

    // 移除实体
    groupAll?.removeAll();
    groupRed?.removeAll();
    groupBlue?.removeAll();
  }
  function reAllStepsList() {
    // 重置所有数据
    redSteps.value = [];
    steps.value = [];
    blueSteps.value = [];
    entityLog.value = { red: [], blue: [] };
    entityIds.value = { red: [], blue: [] };
    entityList.value = { red: [], blue: [] };
    redFireSteps.value = [];
    blueFireSteps.value = [];
    isStart.value = false;
    isPause.value = true;
    simulTime.value = "";
    simulSpeed.value = 1.0;
    defSimulSpeed.value = 1.0;
    currentPerspective.value = "all";
    isShowPath.value = false;
    isShowLabel.value = true;
    isShowFooter.value = true;
    isShowEntityPanel.value = false;
    isShowLogPanel.value = false;
    allIsInit.value = true;
    redIsInit.value = true;
    blueIsInit.value = true;
    redDomainInit.value = true;
    blueDomainInit.value = true;

    // 获取 viewer 实例
    const cesiumStore = cesiumState();
    const customViewer = cesiumStore.getCustomViewer as any;

    if (customViewer && customViewer.animationManager) {
      // 移除所有动画组
      customViewer.animationManager.removeAnimationGroup(EntityGroupId.all);
      customViewer.animationManager.removeAnimationGroup(EntityGroupId.red);
      customViewer.animationManager.removeAnimationGroup(EntityGroupId.blue);

      // 清除路径
      if (routesManager.value) {
        routesManager.value.removePath();
      }

      // 重置初始化标志
      allIsInit.value = true;
      redIsInit.value = true;
      blueIsInit.value = true;
    }
  }

  function exitToClear() {
    isStart.value = false;
    isPause.value = true;
    simulTime.value = "";
    simulSpeed.value = 1.0;
    defSimulSpeed.value = 1.0;
    currentPerspective.value = "all";
    isShowPath.value = false;
    isShowLabel.value = true;
    isShowFooter.value = true;
    isShowEntityPanel.value = false;
    isShowLogPanel.value = false;
    allIsInit.value = true;
    redIsInit.value = true;
    blueIsInit.value = true;
    clientId.value = createGuid();
    steps.value = [];
    redSteps.value = [];
    blueSteps.value = [];
    redFireSteps.value = [];
    blueFireSteps.value = [];
    // 实体列表
    entityList.value = {
      red: [],
      blue: [],
    };
    // 日志
    entityLog.value = {
      red: [],
      blue: [],
    };
    // 实时轨迹
    routesManager.value && (routesManager.value.entityRoutes = {});
  }

  // 批量设置步骤数据的函数
  function setAllSteps(newSteps: ISideStep[]) {
    steps.value = newSteps;
  }

  function setRedSteps(newSteps: ISideStep[]) {
    redSteps.value = newSteps;
  }

  function setBlueSteps(newSteps: ISideStep[]) {
    blueSteps.value = newSteps;
  }

  return {
    isStart,
    isPause,
    simulTime,
    simulSpeed,
    defSimulSpeed,
    clientId,
    currentPerspective,
    isShowLabel,
    isShowPath,
    isShowFooter,
    isShowEntityPanel,
    isShowLogPanel,
    isShowInfoDomain,
    isShowFireDomain,
    steps,
    redSteps,
    blueSteps,
    redDomainInit,
    blueDomainInit,
    allIsInit,
    redIsInit,
    blueIsInit,
    routesManager,
    domainManager,
    entityList,
    entityLog,
    entityIds,
    redFireSteps,
    blueFireSteps,
    getIsPause,
    getSimulTime,
    getSimulSpeed,
    subscribeFireAndInformation,
    updateFireAndInfoAtStep,
    loadLocalData,
    applyStepData,
    initializeEntityList,
    processObservationData,
    updateDomainShow,
    getDomainShow,
    reAllStepsList,
    updateLabelShow,
    addStep,
    addRedStep,
    addBlueStep,
    setAllIsInit,
    setRedIsInit,
    setBlueIsInit,
    setIsPause,
    setSimulTime,
    setSimulSpeed,
    restart,
    exitToClear,
    setAllSteps,
    setRedSteps,
    setBlueSteps,
  };
});

// 辅助函数
function changeView(customViewer: CustomViewer, currentPerspective: string) {
  // 导演
  const groupAll = customViewer.animationManager?.getAnimationGroup(
    EntityGroupId.all
  );
  // 红方
  const groupRed = customViewer.animationManager?.getAnimationGroup(
    EntityGroupId.red
  );
  // 蓝方
  const groupBlue = customViewer.animationManager?.getAnimationGroup(
    EntityGroupId.blue
  );

  switch (currentPerspective) {
    case "all":
      groupAll && (groupAll.datasource.show = true);
      groupRed && (groupRed.datasource.show = false);
      groupBlue && (groupBlue.datasource.show = false);
      break;

    case "red":
      groupRed && (groupRed.datasource.show = true);
      groupAll && (groupAll.datasource.show = false);
      groupBlue && (groupBlue.datasource.show = false);
      break;

    case "blue":
      groupBlue && (groupBlue.datasource.show = true);
      groupAll && (groupAll.datasource.show = false);
      groupRed && (groupRed.datasource.show = false);
      break;

    default:
      break;
  }
}

function handleTimeDuration(simul_time: string): string {
  let totalSeconds = moment.duration(simul_time, "seconds");
  let hours = Math.floor(totalSeconds.asHours());
  let minis = Math.floor(totalSeconds.asMinutes()) - hours * 60;
  let seconds =
    Math.floor(totalSeconds.asSeconds()) - hours * 60 * 60 - minis * 60;
  return (
    (hours < 10 ? "0" + hours : hours) +
    ":" +
    (minis < 10 ? "0" + minis : minis) +
    ":" +
    (seconds < 10 ? "0" + seconds : seconds)
  );
}
